<template>
    <span @click="toUpdateUser">
        {{command}}
    </span>
    <el-dialog v-model="centerDialogVisible" :title="command" width="40%" center :append-to-body='true'>
        <el-skeleton :rows="3" animated :loading="loading">
            <el-form :model="userData">
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
                    <el-input v-model="userData.userName" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="头像" :label-width="formLabelWidth" prop="userAvatar">
                  <el-upload
                      class="avatar-uploader"
                      action="http://localhost:8101/api"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="上传头像" />
                    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="性别" :label-width="formLabelWidth" prop="sex">
                    <el-radio-group v-model="userData.sex">
                        <el-radio :label="0" value="0">男</el-radio>
                        <el-radio :label="1" value="1">女</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </el-skeleton>
        <template #footer>
                <span class="dialog-footer">
                    <el-button @click="centerDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="updateUser">确认</el-button>
                </span>
        </template>
    </el-dialog>
</template>

<script setup>
import {inject, onBeforeMount, onMounted, reactive, ref} from "vue";
import myAxios from "../../plugins/myAxios.js";
import {
  ElMessage,ElUpload
} from "element-plus";
import { Plus } from '@element-plus/icons-vue'

const props = defineProps(["command"])
const centerDialogVisible = ref(false)
const formLabelWidth = '140px'
const loading = ref(true);

const userRef = inject('userRef');

const userData = ref({
        id:'undefined',
        userName:'undefined',
        userAvatar:'undefined',
        sex:'undefined',
})

const imageUrl = ref('');

// const { handleAvatarSuccess, beforeAvatarUpload } = ElUpload({
//   onSuccess: (response, file) => {
//     imageUrl.value = URL.createObjectURL(file.raw);
//   },
//   beforeUpload: (file) => {
//     if (file.type !== 'image/jpeg/png') {
//       ElMessage.error('头像格式不正确');
//       return false;
//     } else if (file.size / 1024 / 1024 > 2) {
//       ElMessage.error('图片大小超出2MB限制 ');
//       return false;
//     }
//     return true;
//   }
// });


const toUpdateUser = ()=>{
    centerDialogVisible.value = true;
    getUser();
}

//获取当前登录用户
const getUser = async ()=>{
    const res = await myAxios.get('/user/get/login')
    if(res.code === 0 && res.data){
        // userData.value = res.data;
        userData.value.id = res.data.id;
        userData.value.userName = res.data.userName;
        userData.value.userAvatar = res.data.userAvatar;
        userData.value.sex = res.data.sex;
        loading.value = false;
    }else{
        userData.value.id = -1;
    }
}

/**
 * 这里userRef和logo页的userRef是响应式
 * 为了避免在更新页对userRef的改变影响对logo的直接影响,这里直接再请求一次，拿到当前登录的用户信息
 * 更新完成之后，更改userRef的引用。
 *
 * 第二种解决办法
 * 因为logo只需要name和avatar变量，所以可以将这两个变量设置为全局上下文变量。
 *
 * 但是如果在这里又请求一次，就不用使用全局store了。
 */
const updateUser = async ()=>{
    const res = await myAxios.post('/user/update/my',{
        userName:userData.value.userName,
        userAvatar:userData.value.userAvatar,
        sex:userData.value.sex,
    })
    if(res.code === 0 && res.data){
        //更新logo页的用户名和头像显示
        userRef.value.userName = userData.value.userName;
        userRef.value.userAvatar = userData.value.userAvatar;
        userRef.value.sex = userData.value.sex;
        userRef.value.id = userData.value.id;
        ElMessage.success("更新成功")
    }else{
        ElMessage.error("更新失败")
    }
    centerDialogVisible.value = false
}


</script>

<style scoped lang="less">
.el-dialog{
    border-radius: 10px;
}
.el-select {
    //width: 300px;
}
.el-input {
    //width: 300px;
}
.dialog-footer button:first-child {
    margin-right: 10px;
}

//上传头像
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

</style>